#!-*- coding:utf8 -*-
import sys
import salt.client

class GetInfo(object):
    def __init__(self):
        self.client = salt.client.LocalClient()
        self.ret = self.client.cmd('*','grains.items')
        self.cmdbinfo = {}
        self.hosts = self.ret.keys()
        for host in self.hosts:
            self.cmdbinfo[host] = {}


    def get_hostname(self):
        return self.ret.keys()

    def get_os(self):
        for host in self.hosts:
            self.cmdbinfo[host]['os'] = self.ret[host].get('os')
        return self.cmdbinfo

    def get_release(self):
        for host in self.hosts:
            self.cmdbinfo[host]['release'] = self.ret[host].get('osrelease')

        return self.cmdbinfo

    def get_ip(self):
        # ip_wan,ip_lan
        '''
        1. 识别ip 内外or 外网
        2. 区别ipv4 ipv6
        '''
        for host in self.get_hostname():
            ips = self.ret[host]['ip_interfaces']
            ips.pop('lo')
            interface = []
            for inter in ips.keys():
                interface.append(inter)
            if 'eth0' in interface and 'eth1' in interface:
                self.cmdbinfo[host]['ip_lan'] = ips['eth0'][0]
                self.cmdbinfo[host]['ip_wan'] = ips['eth1'][0]
            elif len(interface) == 1:
                # print('--log get_info 46 : interface count 1 ')
                self.cmdbinfo[host]['ip_lan'] = '127.0.0.1'
                self.cmdbinfo[host]['ip_wan'] = ips[interface[0]][0]
            else:
                # print('--log get_info 50 : interface name other ')
                self.cmdbinfo[host]['ip_wan'] = ips[interface[0]][0]
                self.cmdbinfo[host]['ip_lan'] = ips[interface[1]][0]


        return self.cmdbinfo

    def get_config_overview(self):
        # 硬件配置概览
        config = '%sc/%sM/%sG'
        for host in self.hosts:
            cpu = self.ret[host]['num_cpus']
            mem = self.ret[host]['mem_total']
            disk = self.ret[host]['disk_total']
            self.cmdbinfo[host]['configureations'] = config%(cpu,mem,disk)

        return self.cmdbinfo

    def run(self):
        self.get_ip()
        self.get_os()
        self.get_release()
        self.get_config_overview()
        return self.cmdbinfo


if __name__ == '__main__':
    getinfo = GetInfo()
    getinfo.get_config_overview()
